package com.example.concurrentprogramming8016.reetrantlock;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author liyanhao
 * @Date 2023-01-05 19:00
 * 获取锁失败
 */
@Slf4j
public class ReentrantLockDemo4 {
    public static void main(String[] args) throws InterruptedException {
        ReentrantLock lock = new ReentrantLock();
        Thread t1 = new Thread(() -> {
            log.debug("t1线程启动了...");
            //注意 即使是设置公平锁，此方法也会立即返回获取锁是否成功，公平锁策略不生效
            if (!lock.tryLock()) {
                log.debug("t1获取锁失败，立即返回false");
                return;
            }
            log.debug("t1获得了锁");
            lock.unlock();
        }, "t1");

        lock.lock();
        log.debug("main线程获得了锁");
        t1.start();
        TimeUnit.SECONDS.sleep(2);
        lock.unlock();
    }
}
